package com.du.dumall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.du.dumall.common.constant.ProductConstant;
import com.du.dumall.product.dao.AttrAttrgroupRelationDao;
import com.du.dumall.product.dao.AttrGroupDao;
import com.du.dumall.product.dao.CategoryDao;
import com.du.dumall.product.entity.AttrAttrgroupRelationEntity;
import com.du.dumall.product.entity.AttrGroupEntity;
import com.du.dumall.product.entity.CategoryEntity;
import com.du.dumall.product.service.AttrGroupService;
import com.du.dumall.product.vo.AttrVo;
import com.du.dumall.product.vo.PageAttrVo;
import com.du.dumall.product.vo.WithattrVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.du.dumall.common.utils.PageUtils;
import com.du.dumall.common.utils.Query;

import com.du.dumall.product.dao.AttrDao;
import com.du.dumall.product.entity.AttrEntity;
import com.du.dumall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService{


    @Autowired
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    AttrGroupDao attrGroupDao;


    @Autowired
    AttrGroupService attrGroupService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.save(attrEntity);
        if (attrEntity.getAttrType().compareTo(ProductConstant.AttrEnum.ATTR_TYPE_BASE.getId()) == 0) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationDao.insert(relationEntity);
        }
    }

    @Override
    public PageUtils queryBasePage(Map<String, Object> params, Long catId, String attrType) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>();
        queryWrapper.eq("attr_type", "base".equalsIgnoreCase(attrType) ? 1 : 0);
        if (catId > 0) {
            queryWrapper.eq("catelog_id", catId);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and((wrapper) -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        List<AttrEntity> records = page.getRecords();
        List<PageAttrVo> pageAttrVos = records.stream().map((attrEntity) -> {
            PageAttrVo pageAttrVo = new PageAttrVo();
            BeanUtils.copyProperties(attrEntity, pageAttrVo);

            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                pageAttrVo.setCatelogName(categoryEntity.getName());
            }

            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
            if (relationEntity != null) {
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                pageAttrVo.setGroupName(attrGroupEntity.getAttrGroupName());
            }


            return pageAttrVo;
        }).collect(Collectors.toList());
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(pageAttrVos);

        return pageUtils;
    }

    @Override
    public PageAttrVo getAttrInfo(Long attrId) {
        PageAttrVo pageAttrVo = new PageAttrVo();
        AttrEntity attrEntity = this.baseMapper.selectById(attrId);
        BeanUtils.copyProperties(attrEntity, pageAttrVo);
        //1.分类信息

        AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
        if (relationEntity != null) {
            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
            if (attrGroupEntity != null) {
                pageAttrVo.setGroupName(attrGroupEntity.getAttrGroupName());
                pageAttrVo.setAttrGroupId(relationEntity.getAttrGroupId());
            }

        }

        //2 分组信息

        Long catelogId = attrEntity.getCatelogId();
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (categoryEntity != null) {
            Long[] catelogPath = attrGroupService.getCatelogPath(catelogId);
            pageAttrVo.setCatelogPath(catelogPath);
            pageAttrVo.setCatelogName(categoryEntity.getName());
        }

        return pageAttrVo;
    }

    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.baseMapper.updateById(attrEntity);

        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        relationEntity.setAttrId(attr.getAttrId());
        relationEntity.setAttrGroupId(attr.getAttrGroupId());

        if (attrEntity.getAttrType().compareTo(ProductConstant.AttrEnum.ATTR_TYPE_BASE.getId()) == 0) {
            Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if (count > 0) {
                attrAttrgroupRelationDao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            } else {
                attrAttrgroupRelationDao.insert(relationEntity);
            }
        }


    }

    @Override
    public List<AttrEntity> listRelation(Long attrGroupId) {
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));
        if (relationEntities != null && relationEntities.size() > 0) {
            List<Long> longs = relationEntities.stream().map((entity) -> {

                return entity.getAttrId();
            }).collect(Collectors.toList());
            Collection<AttrEntity> entities = this.listByIds(longs);
            return (List<AttrEntity>) entities;
        }
        return null;
    }

    @Override
    public PageUtils noattrRelation(Map<String, Object> params, Long attrGroupId) {
        if (attrGroupId > 0) {
            List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));

            List<Long> longs = relationEntities.stream().map((entity) -> {
                return entity.getAttrId();
            }).collect(Collectors.toList());

            QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
            if (longs != null && longs.size() > 0) {
                queryWrapper.notIn("attr_id", longs);
            }
            IPage<AttrEntity> page = this.page(
                    new Query<AttrEntity>().getPage(params),
                    queryWrapper
            );
            return new PageUtils(page);
        }

        return null;
    }

    @Override
    public  List<WithattrVo> withattrList(Long catId) {
        List<WithattrVo> withattrVos = new ArrayList<>();
        List<AttrGroupEntity> attrGroupEntities = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catId));
        List<WithattrVo> withattrVoList = attrGroupEntities.stream().map((item) -> {
            WithattrVo vo = new WithattrVo();
            BeanUtils.copyProperties(item, vo);
            List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", item.getAttrGroupId()));
            List<AttrEntity> collect = relationEntities.stream().map((attrgroupRelationEntity) -> {
                return this.baseMapper.selectById(attrgroupRelationEntity.getAttrId());
            }).collect(Collectors.toList());
            vo.setAttrs(collect);
            return vo;
        }).collect(Collectors.toList());
        return withattrVoList;
    }

}